package com.zg.third.qcc.utils;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zg.third.qcc.enm.ZtQccUrlEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 企查查工具类
 */
@Slf4j
@Component
public class QccUtil {

    private static String appKey;
    private static String secretKey;
    private static String domain;

    @Value("${qcc.AppKey}")
    public void setAppKey(String appKey) {
        QccUtil.appKey = appKey;
    }

    @Value("${qcc.secretKey")
    public void setSecretKey(String secretKey) {
        QccUtil.secretKey = secretKey;
    }

    @Value("${qcc.domain}")
    public void setDomain(String domain) {
        QccUtil.domain = domain;
    }



    public static  String request(String apiCode,Map<String, Object> requestParam) {

        // 3. 生成签名（企查查API要求的签名逻辑）
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000); // 时间戳（秒级）
        requestParam.put("key",appKey);
        log.info("KYC接口请求参数: {}", requestParam);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json;charset=UTF-8");
        headers.put("Timestamp", timestamp);
        headers.put("Token", generateSignature(timestamp));

        String requestUrl = domain + ZtQccUrlEnum.getByApiCode(apiCode).getUrl();
        log.info("请求地址:"+requestUrl);
        String result = HttpUtil.createPost(requestUrl)
                .addHeaders(headers)
                .body(JSONUtil.toJsonStr(requestParam))
                .execute()
                .body();
        log.info("KYC接口返回报文: {}", result);

        return result;
    }

    /**
     * 生成企查查API签名（按官网规范实现）
     * 签名规则：SHA256(appKey + appSecret + timestamp + nonce) 转大写
     */
    private static String generateSignature(String timestamp) {
        String signSource = appKey  + timestamp + secretKey;
        return DigestUtil.md5Hex(signSource).toUpperCase();
    }
}
